<template>
  <div class="user">
    <!-- 上方搜索栏 -->
    <el-card class="search">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名">
          <el-input placeholder="请输入要搜索的用户名" v-model="searchUserName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 下方用户列表 -->
    <el-card class="list">
      <!-- 上方按钮组 -->
      <el-button 
        type="primary" 
        @click="showDialog({id:0})"
      >新增用户</el-button>
      <el-button 
        type="danger" 
        :disabled="isDisabled" 
        @click="handleMutilDeleteUser"
      >批量删除</el-button>

      <!-- 中间表格 -->
      <el-table :data="userData" border class="table" @selection-change="selectDeleteUser">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column type="index" :index="(index) => (curPage - 1) * pageSize + index + 1" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="name" label="用户名" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center"></el-table-column>
        <el-table-column prop="last_login_time" label="上次登录时间" align="center"></el-table-column>
        <el-table-column prop="last_login_ip" label="上次登录IP" width="130" align="center"></el-table-column>
        <el-table-column prop="role_descriptions" label="角色" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column label="操作" class="buttons" width="300" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="showDialog(scope.row)">修改数据</el-button>
            <el-button type="danger" size="small" @click="showDeleteDialog(scope.row.id)">删除用户</el-button><br>
            <el-button type="info" size="small" @click="showAssignRoleDrawer(scope.row)" class="btn">赋予角色</el-button>
            <el-button type="danger" size="small" class="btn" @click="showUnassignRoleDrawer(scope.row)">移除角色</el-button><br>
          </template>
        </el-table-column>
      </el-table>

      <!-- 下方分页器 -->
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="curPage"
        :page-sizes="pageSizeArr"
        :page-size="pageSize"
        :total="totalRecord"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange">
      </el-pagination>
    </el-card>

    <!-- 新增或修改用户弹窗 -->
    <el-dialog
      :title="rowUserId > 0 ? '修改用户' : '新增用户'"
      :visible.sync="isShowSaveDialog"
      width="50%">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input placeholder="请输入用户名" v-model="userDataSave.name"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input placeholder="请输入密码" show-password v-model="userDataSave.password"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="userDataSave.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click='isShowSaveDialog = false;Object.assign(userDataSave,{id:0,name:"",password:"",last_login_time:"",last_login_ip:"",status:0});'>取 消</el-button>
        <el-button type="primary" @click="handleSaveUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除用户弹窗 -->
    <el-dialog
      title="删除用户"
      :visible.sync="isShowDeleteDialog"
      width="50%">
      <span>您确认需要删除此用户信息？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click='isShowDeleteDialog = false;'>取 消</el-button>
        <el-button type="primary" @click="handleDeleteUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 赋予角色抽屉 -->
    <el-drawer title="赋予角色" :visible.sync="isShowAssignRoleDrawer">
      <el-form style="padding: 20px">
        <p style="font-size:1.3rem">当前用户：<span class="name">{{ rowUserName }}</span></p>
        <el-form-item>
          <el-checkbox-group v-model="selectedRoleIds" style="margin-top:20px">
            <el-checkbox 
              v-for="role in roleListForAssign" 
              :key="role.id" 
              :label="role.id" 
              :disabled="role.isDisabled || role.isChecked">
              {{ role.description }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleAssignRole">确 定</el-button>
          <el-button @click="isShowAssignRoleDrawer = false">取 消</el-button>
        </el-form-item>

      </el-form>
    </el-drawer>

    <!-- 移除角色抽屉 -->
    <el-drawer title="移除角色" :visible.sync="isShowUnassignRoleDrawer">
      <el-form style="padding: 20px">
        <p style="font-size:1.3rem">当前用户：<span class="name">{{ rowUserName }}</span></p>
        <template v-if="roleListForUnassign.length > 0">
          <el-form-item>
            <el-checkbox-group v-model="selectedRoleIds" style="margin-top:15px">
              <el-checkbox 
                v-for="role in roleListForUnassign" 
                :key="role.id" 
                :label="role.id">
                {{ role.description }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleUnassignRole">确 定</el-button>
            <el-button @click="isShowUnassignRoleDrawer = false">取 消</el-button>
          </el-form-item>
        </template>
        <template v-else>
          <p style="color:grey;font-size:0.9rem;font-weight:light;text-align:center;margin-top:30px">暂无角色数据,请先添加<br>角色</p>
        </template>
      </el-form>
    </el-drawer>

  </div>
</template>

<script>
import { mapActions,mapMutations,mapState } from 'vuex';
import { Message } from 'element-ui';

export default {
  name: "UserView",
  data(){
    return{
      //  数据总数
      totalRecord:0,
      //  当前页码
      curPage:1,
      //  每页展示数据的数量
      pageSize:5,
      //  下拉框数组
      pageSizeArr:[5,10,20,30,50],
      //  需要搜索用户名
      searchUserName: "",
      //  所有用户数据
      userData:[],
      //  添加或更新用户的对话框显示与否
      isShowSaveDialog:false,
      //  需要添加或更新的用户数据
      userDataSave:{
        id:0,
        name:"",
        password:"",
        last_login_time:"",
        last_login_ip:"",
        status:1
      },
      //  删除用户的对话框显示与否
      isShowDeleteDialog:false,
      //  批量删除按钮的禁用与否
      isDisabled:true,
      //  批量移除用户的勾选的复选框的id
      multiDeleterUserIdArr:[],
      //  赋予角色抽屉的显示与否
      isShowAssignRoleDrawer:false,
      //  赋予或移除角色的勾选的复选框的id
      selectedRoleIds: [],
      //  移除角色抽屉的显示与否
      isShowUnassignRoleDrawer:false,
    }
  },
  methods:{
    ...mapMutations("userStore",{ 
      setRowUserId: "setRowUserId",
      setRowUserName: "setRowUserName"
    }),
    ...mapActions("userStore", { 
      userList: "userList",
      userAdd: "userAdd",
      userUpdate: "userUpdate",
      userDelete:"userDelete",
      userAllDelete:"userAllDelete",
      userRoles: "userRoles",
      userAssignRoles: "userAssignRoles",
      userRemoveRoles: "userRemoveRoles"
    }),
    ...mapActions("roleStore",{
      roleList: "roleList",
      getRoleListForAssign: "getRoleListForAssign",
      getRoleListForUnassign: "getRoleListForUnassign"
    }),
    
    //  搜索
    handleSearch() {
      this.curPage = 1;
      this.getUserData(this.searchUserName);
    },
    //  重置
    handleReset() {
      this.searchUserName = '';
      this.curPage = 1;
      this.getUserData();
    },
    

    //  获取用户数据
    async getUserData(name){
      try {
        if (name) {
          this.searchUserName = name;
        }
        const result = await this.userList({
          curPage:this.curPage,
          pageSize:this.pageSize,
          name: this.searchUserName
        });
        this.totalRecord = result.total;
        this.userData = result.data;
      } catch (error) {
        Message({
          type: "error",
          message:error.message,
        });
      } 
    },


    //  分页器
    handleCurrentChange(val) {
      this.curPage = val;
      this.getUserData();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.curPage = 1; 
      this.getUserData();
    },


    //  添加或更新用户信息
    showDialog(obj){
      this.isShowSaveDialog = true;
      this.setRowUserId(obj.id);
    },

    async handleSaveUser(){
      try{
        if(this.rowUserId > 0){
          //  id存在更新
          this.userDataSave.id = this.rowUserId;
          const data = await this.userUpdate(this.userDataSave);
          Message({
            type: "success",
            message:data.msg
          });
          
        }else{
          //  id不存在则新增
          const data = await this.userAdd(this.userDataSave);
          Message({
              type: "success",
              message:data.msg
          });
        }
      }catch(error){
        Message({
          type: "error",
          message:error.message,
        });
      }finally{
        this.isShowSaveDialog = false;
        Object.assign(this.userDataSave,{id:0,name:"",password:"",last_login_time:"",last_login_ip:"",status:0});
        this.getUserData();
      }
    },


    //  删除用户信息
    showDeleteDialog(id){
      this.isShowDeleteDialog = true;
      this.setRowUserId(id);
    },

    async handleDeleteUser(){
      try{
        if(this.rowUserId > 0){
          const data = await this.userDelete({
            id:this.rowUserId
          });
          Message({
            type: "success",
            message:data.msg
          });
        }
      }catch(error){
        Message({
          type: "error",
          message:error.message,
        });
      }finally{
        this.isShowDeleteDialog = false;
        this.getUserData();
      }
    },


    //  批量删除角色信息
    selectDeleteUser(userArr){
      this.multiDeleterUserIdArr = [];
      if(userArr.length > 0){
        this.isDisabled = false;
        userArr.forEach(userId => {
          this.multiDeleterUserIdArr.push(userId.id);
        });
      }else{
        this.isDisabled = true;
      }
    },

    async handleMutilDeleteUser(){
      try {
        const data = await this.userAllDelete(this.multiDeleterUserIdArr);
        Message({
          type: "success",
          message:data.msg
        });
      } catch (error) {
        Message({
          type: "error",
          message:error.message,
        });
      } finally {
        this.isDisabled = true;
        this.multiDeleterUserIdArr = [];
        this.getUserData();
      }
    },


    //  给用户赋予角色
    async showAssignRoleDrawer(obj){
      this.isShowAssignRoleDrawer = true;
      this.setRowUserId(obj.id);
      this.setRowUserName(obj.name);
      try {
        //  获取所有的角色信息
        const allRoles = await this.roleList({
          limit: 100, 
          page: 1
        });
        //  获取当前选中用户的所有角色信息
        const userRoles = await this.userRoles({
          user_id: this.rowUserId
        });
        //  处理数据
        await this.getRoleListForAssign([allRoles.data, userRoles.id]);
        this.selectedRoleIds = [];
      } catch (error) {
        Message({
          type: "error",
          message: error.message 
        });
      }
    },

    async handleAssignRole() {
      try {
        if(this.selectedRoleIds.length > 0) {
          const result = await this.userAssignRoles({
            user_id: this.rowUserId,
            role_id: this.selectedRoleIds
          });
          Message({
            type: "success",
            message: result.msg
          });
        } else {
          Message({
            type: "warning",
            message: "请至少选择一个角色"
          });
        }
      } catch (error) {
        Message({
          type: "error",
          message: error.message
        });
      } finally {
        this.isShowAssignRoleDrawer = false;
        this.selectedRoleIds = [];
        this.getUserData();
      }
    },


    //  移除用户角色
    async showUnassignRoleDrawer(obj){
      try{
        this.isShowUnassignRoleDrawer = true;
        this.setRowUserId(obj.id);
        this.setRowUserName(obj.name);
        const userRoles = await this.userRoles({
          user_id: this.rowUserId
        });
        await this.getRoleListForUnassign(userRoles);
        this.selectedRoleIds = [];
      }catch(error){
        Message({
          type: "error",
          message:error.message,
        });
      }
    },

    async handleUnassignRole(){
      try{
        if(this.selectedRoleIds.length > 0) {
          const result = await this.userRemoveRoles({
            user_id: this.rowUserId,
            role_id: this.selectedRoleIds
          });
          Message({
            type: "success",
            message: result.msg
          });
        } else {
          Message({
            type: "warning",
            message: "请至少选择一个角色"
          });
        }
      }catch(error){
        Message({
          type: "error",
          message: error.message
        });
      }finally{
        this.isShowUnassignRoleDrawer = false;
        this.selectedRoleIds = [];
        this.getUserData();
      }
    }
  },
  mounted(){
    this.getUserData();
  },
  computed:{
    ...mapState("userStore",{ 
      rowUserId: "rowUserId", 
      rowUserName: "rowUserName"
    }),
    ...mapState("roleStore",{ 
      roleListForAssign: "roleListForAssign",
      roleListForUnassign: "roleListForUnassign"
    })
  }
}
</script>

<style scoped lang="scss">
.user{
  margin: 0 auto;
  width:95%;
  .search{
    height: 80px;
    .form{
      display: flex;
      justify-content: space-between;
    }
  }
  .list{
    margin-top: 30px;
    .table{
      margin: 20px 0;
      .btn{
        margin-top: 10px;
      }
    }
  }
}
.name{
  color: $main_color;
  font-weight: bold;
}
</style>